package org.example.market.controller;

import org.example.market.entity.Bill;

import org.example.market.entity.BillCountVO;
import org.example.market.entity.RecentBillAmountVO;
import org.example.market.entity.RecentBillCountVO;
import org.example.market.mapper.BillMapper;
import org.example.market.service.BillService.BillService;
import org.example.market.util.DailyAmount;
import org.example.market.util.DailyCount;
import org.example.market.util.PageResult;
import org.example.market.util.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/bill")
public class BillController {

    @Autowired
    private BillService billService;
    @Autowired
    private BillMapper billMapper;

    @PostMapping
    public Result<Bill> addBill(@RequestBody Bill bill) {
        return billService.addBill(bill);
    }

    @GetMapping("/list")
    public Result<PageResult<Bill>> getBillList(
            @RequestParam(defaultValue = "1") int currentPage,
            @RequestParam(defaultValue = "5") int pageSize,
            @RequestParam(required = false) String productName,
            @RequestParam(required = false) Integer providerId,
            @RequestParam(required = false) Integer isPayment) {
        return billService.getBillList(currentPage, pageSize, productName, providerId, isPayment);
    }

    @PutMapping
    public Result<Bill> updateBill(@RequestBody Bill bill) {
        return billService.updateBill(bill);
    }

    @DeleteMapping("/{id}")
    public Result<Void> deleteBill(@PathVariable Long id) {
        return billService.deleteBill(id);
    }

    @GetMapping("/{id}")
    public Result<Bill> getBillById(@PathVariable Long id) {
        return billService.getBillById(id);
    }

    /**
     * 获取账单统计数量（今日、昨日、本周、本月）
     * @return 统计结果
     */
    @GetMapping("/count")
    public Result<BillCountVO> getBillCounts() {
        return billService.getBillCounts();
    }

    /**
     * 获取最近7天账单数量趋势
     * @return 统计结果
     */
    @GetMapping("/recent/count")
    public Result<List<RecentBillCountVO>> getRecentBillCounts() {
        return billService.getRecent7DaysBillCount();
    }

    /**
     * 获取最近7天账单金额趋势
     * @return 统计结果
     */
    @GetMapping("/recent/amount")
    public Result<List<RecentBillAmountVO>> getRecentBillAmounts() {
        return billService.getRecent7DaysBillAmount();
    }

    // 新增：检查账单编码唯一性
    @GetMapping("/checkCode")
    public Result<Void> checkBillCodeUnique(@RequestParam String billCode) {
        Bill existBill = billMapper.getBillByCode(billCode);
        if (existBill != null) {
            return Result.error("账单编码已存在");
        }
        return Result.success();
    }
}